package cn.itcast.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

import static cn.itcast.nio.c1.ByteBufferUtil.debugAll;

@Slf4j
public class ServerV2 {

    public static void main(String[] args) throws IOException {
        //1.创建selector,管理多个channel
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        //2.建立selector和channel的联系（注册）
        //SelectionKey 就是将来事件发生后，通过它可以知道事件和哪个channel的事件
        SelectionKey sscKey = ssc.register(selector,0,null);

        // key 只关注accept事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        log.debug("register key:{}",sscKey);

        ssc.bind(new InetSocketAddress(8080));
        while (true) {
            // 3.select 方法，没有事件发生，线程阻塞，有事件，线程才会恢复运行
            // select 在事件未处理时，它不会阻塞，事件发生后要么处理，要么取消，不能置之不理
            selector.select();
            // 4.处理事件，selectKeys 内部包含了所有发生的事件
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                //处理key时，要从selectKeys集合中删除，否则下次处理就会有问题
                iterator.remove();
                log.debug("key:{}",key);

                //5.区分事件类型
                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel)key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);

                    //将一个bytebuffer作为附件关联到 selectKey上
                    ByteBuffer buffer = ByteBuffer.allocate(16);//attachment
                    SelectionKey scKey = sc.register(selector, 0, buffer);
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("sc:{}",sc);
                    log.debug("scKey:{}",sc);
                }else if (key.isReadable()){
                    try {
                        SocketChannel channel = (SocketChannel)key.channel();
                        //获取selectKey上关联的附件
                        ByteBuffer buffer = (ByteBuffer)key.attachment();
                        System.out.println("进入时buffer长度："+buffer.limit());

                        int read = channel.read(buffer);//如果是正常断开，read的方法返回值是 -1
                        if (read == -1){
                            key.cancel();
                        }else {
                            split(buffer);
//                            System.out.println("body ：： "+Charset.defaultCharset().decode(buffer));
                            if (buffer.position() == buffer.limit()){
                                ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity()*2);
                                buffer.flip();
                                newBuffer.put(buffer);
                                key.attach(newBuffer);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        //客户端断开链接，因此需要将Key从selector中移除
                        key.cancel();
                    }
                }
            }
        }
    }


    private static void split(ByteBuffer source){
        source.flip();
        for (int i = 0; i < source.limit() ; i++) {
            //根据分割符号 找到完整消息
            if (source.get(i) == '\n'){
                //获取完整消息的长度
                int length = i + 1 - source.position();
//                System.out.println("I="+i+",length:"+length+",position:"+ source.position());

                ByteBuffer target = ByteBuffer.allocate(length);
                //写入获取字符
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }

                debugAll(target);
            }
        }

        source.compact();
    }
}
